package models;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import objects.FeaturesDatabase;
import objects.Constituent;
import objects.Feature;

/* Accessible only through FeaturesModel */
class FeatureXMLWriter {
	
	private FeaturesDatabase db;
	
	public FeatureXMLWriter() {
		db = null;
	}
	
	public void write(String fileLocation) throws FileNotFoundException, IOException {
		Element theRoot = putXML();

		Document doc = new Document(theRoot);
		XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat());
		xmlOutput.output(doc, new FileOutputStream(new File(fileLocation)));
	}
	
	public Element putXML() {
		Element theRoot = new Element("featureslist");
		

		if(db.getConstituents() != null) {
			for (Constituent currentConstituent : db.getConstituents()) {
				Element constituent = new Element("constituent");
				
				constituent.setAttribute("label", currentConstituent.getLabel());
				
				
				for (Feature currentFeature : currentConstituent.getFeatures().getFeatureList()) {
					Element feature = new Element("feature");
					
					feature.setAttribute("name", currentFeature.getName());
					feature.setAttribute("editable", "" + currentFeature.isEditable());
					
					for (String currentValue : currentFeature.getValueList()) {
						Element value = new Element("value");
						
						value.setText(currentValue);
						
						feature.addContent(value);
					}
					
					constituent.addContent(feature);
				}
				
				theRoot.addContent(constituent);
			}
		}
		
		return theRoot;
	}
	
	public void setDatabase(FeaturesDatabase db) {
		this.db = db;
	}
	
}
